package crp.core.faculty.domain.repositories;

import com.qwlabs.lang.C2;
import crp.core.department.domain.models.DepartmentEntity;
import crp.core.faculty.domain.models.FacultyDepartmentEntity;
import crp.core.faculty.domain.models.FacultyEntity;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import io.quarkus.panache.common.Parameters;

import javax.enterprise.context.ApplicationScoped;
import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;

import static io.quarkus.panache.common.Parameters.with;

@ApplicationScoped
public class FacultyDepartmentRepository implements PanacheRepositoryBase<FacultyDepartmentEntity, String> {

    public Stream<FacultyDepartmentEntity> findByFacultyIds(Collection<String> facultyIds) {
        return C2.mapNotEmpty(facultyIds, () ->
                        find("faculty.id in (:facultyIds)", with("facultyIds", facultyIds)))
                .map(PanacheQuery::stream)
                .orElse(Stream.empty());
    }

    public Optional<FacultyDepartmentEntity> findBy(FacultyEntity faculty, DepartmentEntity department) {
        return find("faculty=:faculty and department=:department",
                with("faculty", faculty).and("department", department))
                .firstResultOptional();
    }

    public Stream<FacultyDepartmentEntity> findByFacultyId(String facultyId) {
        return find("faculty.id=:facultyId", Parameters.with("facultyId", facultyId))
                .stream();
    }
}
